package org.kongqian.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.time.DateUtils;
import org.kongqian.gift.client.LoginUserClient;
import org.kongqian.gift.domain.Employee;
import org.kongqian.gift.domain.LoginUser;
import org.kongqian.gift.domain.Tenant;
import org.kongqian.gift.dto.TenantSettledDTO;
import org.kongqian.gift.exception.AssertionException;
import org.kongqian.gift.exception.GlobalException;
import org.kongqian.gift.exception.code.ErrorCode;
import org.kongqian.gift.mapper.EmployeeMapper;
import org.kongqian.gift.mapper.TenantMapper;
import org.kongqian.gift.query.TenantQuery;
import org.kongqian.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.kongqian.gift.util.AjaxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kq
 * @since 2022-12-06
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginUserClient loginUserClient;

    @Override
    public AjaxResult selectPageList(TenantQuery query) {
        //封装当前页和每页显示条数
        Page<Object> page = new Page<>(query.getPage(), query.getRows());
        List<Tenant> datas=tenantMapper.selectPageList(page,query);
        PageList<Tenant> list = new PageList<>(page.getTotal(), datas);
        return new AjaxResult().setResultObj(list);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    //@Transactional
    public AjaxResult tenantSettled(TenantSettledDTO dto) {
        Tenant tenant = dto.getTenant();
        Employee admin = dto.getAdmin();
        Long mealId = dto.getMealId();

        //参数校验
        settledVerify(dto, tenant, admin, mealId);
        //百度审核@TODO

        //审核日志@TODO

        //保存管理员登录信息
            //需要登录信息的id
            //远程调用
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(admin, loginUser);
        loginUser.setType(0);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        if (!ajaxResult.isSuccess())
            return ajaxResult;

        //拿到管理员登录信息的Id
        Long loginId=Long.parseLong(ajaxResult.getResultObj().toString());

        //保存管理员
        admin.setLoginId(loginId);
        employeeMapper.insert(admin);

        //保存租户信息
        tenant.setAdminId(admin.getId());
        tenantMapper.insert(tenant);

        //保存套餐和租户的中间表
        HashMap<String, Object> params = new HashMap<>();
        params.put("mealId", mealId);
        params.put("tenantId", tenant.getId());
        params.put("expireDate", DateUtils.addYears(new Date(), 1));
        params.put("state", 0);
        tenantMapper.insertTenantAndMeal(params);

        //发邮件激活@TODO

        return AjaxResult.me();

    }

    //断言异常版
    private void settledVerify(TenantSettledDTO dto, Tenant tenant, Employee admin, Long mealId) {
        //参数校验
        //非空校验
        AssertionException.assertionNotNull(dto, "参数不能为空！");
        AssertionException.assertionNotNull(tenant, "参数不能为空！");
        AssertionException.assertionNotNull(admin, "参数不能为空！");
        AssertionException.assertionNotNull(mealId, "参数不能为空！");

        //两次密码比较是否相同
        AssertionException.assertionStrEq(admin.getPassword(), admin.getConfirmPassword(), ErrorCode.ERROR_CODE_PASSWORD_EQ);

        //判断租户是否已经存在
        EntityWrapper<Tenant> wrapper = new EntityWrapper();
        wrapper.eq("company_name", tenant.getCompanyName());
        List<Tenant> tenants = tenantMapper.selectList(wrapper);
        //存在就提示用户已经入驻了，请登录使用
        AssertionException.assertionListNull(tenants,ErrorCode.ERROR_CODE_TENANT_NOTNULL);

        //判断管理员是否已经存在
        List<Employee> username = employeeMapper
                .selectList(new EntityWrapper<Employee>()
                        .eq("username", admin.getUsername()));
        //存在就提示用户已经存在，请登录后再入驻
        AssertionException.assertionListNull(username,ErrorCode.ERROR_CODE_ADMIN_NOTNULL);
    }

    //自定义异常版
    private void settledVerify2(TenantSettledDTO dto, Tenant tenant, Employee admin, Long mealId) {
        //参数校验
        //非空校验
        if (ObjectUtils.isEmpty(dto)){
            throw new GlobalException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(tenant)){
            throw new GlobalException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(admin)){
            throw new GlobalException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(mealId)){
            throw new GlobalException("参数不能为空！");
        }
        //两次密码比较是否相同
        if (!admin.getPassword().equals(admin.getConfirmPassword())){
            throw new GlobalException("两次密码不一致！");
        }
        //判断租户是否已经存在
        EntityWrapper<Tenant> wrapper = new EntityWrapper();
        wrapper.eq("company_name", tenant.getCompanyName());
        List<Tenant> tenants = tenantMapper.selectList(wrapper);
        //存在就提示用户已经入驻了，请登录使用
        if (!ObjectUtils.isEmpty(tenants)){
            throw new GlobalException("已经入驻了，请登录使用！");
        }
        //判断管理员是否已经存在
        List<Employee> username = employeeMapper
                .selectList(new EntityWrapper<Employee>()
                        .eq("username", admin.getUsername()));
        //存在就提示用户已经存在，请登录后再入驻
        if (!ObjectUtils.isEmpty(username)){
            throw new GlobalException("管理员已经存在，请登录后再入驻！");
        }
    }

    //原始版
    private void settledVerify1(TenantSettledDTO dto, Tenant tenant, Employee admin, Long mealId) {
        //参数校验
        //非空校验
        if (ObjectUtils.isEmpty(dto)){
            throw new RuntimeException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(tenant)){
            throw new RuntimeException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(admin)){
            throw new RuntimeException("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(mealId)){
            throw new RuntimeException("参数不能为空！");
        }
        //两次密码比较是否相同
        if (!admin.getPassword().equals(admin.getConfirmPassword())){
            throw new RuntimeException("两次密码不一致！");
        }
        //判断租户是否已经存在
        EntityWrapper<Tenant> wrapper = new EntityWrapper();
        wrapper.eq("company_name", tenant.getCompanyName());
        List<Tenant> tenants = tenantMapper.selectList(wrapper);
        //存在就提示用户已经入驻了，请登录使用
        if (!ObjectUtils.isEmpty(tenants)){
            throw new RuntimeException("已经入驻了，请登录使用！");
        }
        //判断管理员是否已经存在
        List<Employee> username = employeeMapper
                .selectList(new EntityWrapper<Employee>()
                        .eq("username", admin.getUsername()));
        //存在就提示用户已经存在，请登录后再入驻
        if (!ObjectUtils.isEmpty(username)){
            throw new RuntimeException("管理员已经存在，请登录后再入驻！");
        }
    }
}
